(function() {
    "use strict";
    /**
     * @ngdoc function
     * @name webApp.controller:ItemCtrl
     * @description
     * # ItemCtrl
     * Controller of the webApp
     */
    angular.module("webApp").controller("ItemCtrl", ItemCtrl);

    ItemCtrl.$inject = [
        "$scope",
        "dataService",
        "$location",
        "$state",
        "helper",
        "$timeout",
        "$rootScope",
        "sku",
        "MENU_Data",
        "cacheService"
    ];

    function ItemCtrl(
        $scope,
        dataService,
        $location,
        $state,
        helper,
        $timeout,
        $rootScope,
        sku,
        MENU_Data,
        cacheService
    ) {
        /**
         * listAction   商品显示
         * getItemList  获取商品列表
         * addAction    商品 添加数据  修改数据 初始化
         * itemSkuAdd       增加规格
         * skuDel       删除规格
         * addSku       获取增加的规格数据
         * itemAdd      创建  修改 商品
         * checkItem    测试商品directives
         */
        //商品显示
        $scope.listAction = function() {
            $scope.itemsTotal = 0;
            $scope.sjmodel = 0;
            $scope.pageSize = 10;
            $scope.on_shelves = 1;
            $scope.stype = "ITEM";
            $scope.getItemList();
            $scope.$on("event:up-store-id", function() {
                $scope.store_id = $rootScope.store_id;
                $scope.getItemList();
            });
        };
        //下载商品
        $scope.downloaditemsAction = function() {
            $scope.price_percent = 120.00;
            $scope.pageSize = 10;
            $scope.type = 2;
            $scope.sjmodel = 0;
            $scope.is_main = $rootScope.is_main;
            // console.error("$scope.is_main", $scope.is_main);
            $scope.getdownloaditems();
        }

        //查询商品
        $scope.getdownloaditems = function(pageNo) {
            $scope.pageNo = pageNo ? pageNo : 1;
            var query = {
                page_no: $scope.pageNo,
                page_size: $scope.pageSize,
                store_id: $rootScope.store_id,
                is_main: $scope.is_main,
                type: $scope.type
            };
            $scope.sjmodel = 0;

            if ($scope.keyword) {
                query.keyword = $scope.keyword;
            }

            dataService.downloaditemsGet(query).then(function(list) {
                if (list) {
                    $scope.itemslist = list.list;
                    $scope.itemsTotal = list.total_count;
                }
            });
        }

        //绑定 解除商品
        $scope.savedownloaditems = function(type) {
            if ($scope.sjmodel) {
                async.mapSeries($scope.sjmodel, function(one, callback) {
                        if ($scope.is_main == 1) {
                            dataService.savemainstoreitem({
                                savetype: type,
                                item_id: one.item_id,
                                store_id: $rootScope.store_id
                            }).then(function(r) {
                                if (r.Msg) {
                                    helper.message("错误：" + r.Msg, "error");
                                }
                                callback(null, null);
                            });
                        } else {
                            dataService.savesubstoreitem({
                                savetype: type,
                                item_id: one.item_id,
                                store_id: $rootScope.store_id,
                                price_percent: $scope.price_percent
                            }).then(function(r) {
                                if (r.Msg) {
                                    helper.message("错误：" + r.Msg, "error");
                                }
                                callback(null, null);
                            });
                        }

                    },
                    function(e, r) {
                        $scope.getdownloaditems($scope.pageNo);
                        helper.message("完成！");
                    }
                );
            }
        }

        //获取商品列表
        $scope.getItemList = function(pageNo) {
            $scope.sjmodel = 0;
            var query = {};
            var key = $rootScope.store_id + "ItemCtrl";
            var cache = cacheService.get(key);
            if (pageNo || !cache) {
                $scope.pageNo = pageNo ? pageNo : 1;
                query = {
                    page_no: $scope.pageNo,
                    page_size: $scope.pageSize,
                };
                var itemquery = {};
                var subquery = {};
                if ($scope.keyword) {
                    query.name = $scope.keyword;
                }

                if ($scope.catid) {
                    itemquery.category_id = $scope.catid;
                }

                if ($rootScope.store_id) {
                    itemquery.store_id = $scope.store_id;
                }

                if ($scope.barcode) {
                    subquery.barcode = $scope.barcode;
                }

                if ($scope.sku_outer_id) {
                    subquery.sku_outer_id = $scope.sku_outer_id;
                }

                if ($scope.select_pickpoint_id > 0) {
                    subquery.pickpoint_id = $scope.select_pickpoint_id;
                }

                itemquery.on_shelves = $scope.on_shelves;
                query.query = itemquery;
                query.subquery = subquery;
                cacheService.set(key, query);
            } else {
                query = clone(cache);
                $scope.queryRcache(query);
            }

            var querys = clone(query);
            dataService.itemGet(querys).then(function(list) {
                if (list) {
                    $scope.itemslist = list.items;
                    $scope.itemsTotal = list.total_count;
                }
            });
        };
        $scope.queryRcache = function(query) {
            // console.error(" query", query);
            $scope.pageNo = query.page_no;
            // console.error(" $scope.pageNo", $scope.pageNo);
            $scope.page_size = query.page_size;
            if (query.name) {
                $scope.keyword = query.name;
            }
            if (query.query.category_id) {
                $scope.catid = query.query.category_id;
            }
        };
        //
        $scope.checkAll = function() {
            $scope.sjmodel = angular.copy($scope.itemslist);
        };

        //回调方法 选择商品类型
        $scope.batchSaveStype = function(data) {
            if (data) {
                // console.error("data", data, $scope.sjmodel);
                async.mapSeries($scope.sjmodel,
                    function(item, callback) {
                        var itemdata = {
                            item_id: item.item_id,
                            xtype: data,
                        };
                        dataService.itemUpdate(itemdata).then(function(list) {
                            if (list.Msg) {
                                //有值
                                callback(null, null);
                            } else {
                                callback(null, null);
                            }
                        });
                    },
                    function(e, r) {
                        helper.myAlert("success", null, null, function() {
                            $scope.getItemList($scope.pageNo);
                        });
                    });
            }
        }

        //
        $scope.batchSavePick = function(pickpoint) {
            // console.error("pickpoint", pickpoint);
            if ($scope.sjmodel) {
                async.mapSeries(
                    $scope.sjmodel,
                    function(one, callback) {
                        dataService.itemUpdate({
                                delivery_addrs: pickpoint,
                                item_id: one.item_id
                            })
                            .then(function(r) {
                                if (r.Msg) {
                                    callback(null, null);
                                } else {
                                    callback(null, null);
                                }
                            });
                    },
                    function(e, r) {
                        helper.myAlert("success", null, null, function() {
                            $scope.getItemList($scope.pageNo);
                        });
                    }
                );
            }
        };
        $scope.nocheckAll = function() {
            if ($scope.sjmodel) {
                //循环
                var noData = [];
                var itemList = clone($scope.itemslist);
                for (var i = 0; i < $scope.sjmodel.length; i++) {
                    for (var j = 0; j < itemList.length; j++) {
                        if (itemList[j]) {
                            if ($scope.sjmodel[i].item_id == itemList[j].item_id) {
                                // delete itemList[j];
                                itemList.splice(j, 1);
                            }
                        }
                    }
                }
                $scope.sjmodel = itemList;
                // console.error("noData", itemList);
            } else {
                $scope.sjmodel = [];
            }
        };



        //商品点赞
        $scope.praiseAction = function() {
            $scope.pageSize = 10;
            $scope.getItemPraiseList(1);
            $scope.$on("event:up-store-id", function() {
                $scope.store_id = $rootScope.store_id;
                $scope.getItemPraiseList(1);
            });
        };

        $scope.batchSaveLabel = function(data) {
            // console.error("data", data);
            if (data.length) {
                helper.message("操作中..");
                async.mapSeries($scope.sjmodel, function(item, callback1) {
                        async.mapSeries(data, function(label, callback) {
                                dataService.itemLabelRelationGet({
                                    item_id: item.item_id,
                                    label_id: label
                                }).then(function(list) {
                                    if (list.total_count) {
                                        //有值
                                        callback(null, null);
                                    } else {
                                        var data = {
                                            label_id: label,
                                            item_id: item.item_id,
                                            store_id: $rootScope.store_id
                                        };
                                        dataService.itemLabelRelationAdd(data).then(function(r) {
                                            if (!r.Msg) {
                                                callback(null, null);
                                            } else {
                                                callback(null, null);
                                            }
                                        });
                                    }
                                });
                            },
                            function(e, r) {
                                var tag_ids;
                                _.map(data, function(da, ke) {
                                    if (tag_ids) {
                                        tag_ids = tag_ids + "," + da;
                                    } else {
                                        tag_ids = da;
                                    }
                                });
                                dataService.itemUpdate({
                                    tag_ids: tag_ids,
                                    item_id: item.item_id
                                }).then(function(r) {
                                    callback1(null, null);
                                });
                            });
                    },
                    function(e, r) {
                        helper.myAlert("success");
                    });
            }
        }

        //发货地址回调方法
        $scope.backpickpoint = function(pickpoint) {
            // console.error("pickpoint", pickpoint);
            if (pickpoint) {
                $scope.item.delivery_addrs = pickpoint;
            }
        };
        $scope.getItemPraiseList = function(pageNo) {
            $scope.pageNo = pageNo ? pageNo : "1";
            var query = {
                content: {
                    page_no: $scope.pageNo,
                    page_size: $scope.pageSize,
                    store_id: $rootScope.store_id
                }
            };

            dataService.praiseGet(query).then(function(list) {
                if (list) {
                    $scope.praiselist = list.praise_list;
                    $scope.praiseTotal = list.total_count;
                }
            });
        };

        //商品点赞
        $scope.commentsAction = function() {
            $scope.pageSize = 10;
            $scope.getItemCommentsList(1);
            $scope.$on("event:up-store-id", function() {
                $scope.store_id = $rootScope.store_id;
                $scope.getItemCommentsList(1);
            });
        };

        $scope.getItemCommentsList = function(pageNo) {
            var query = {};
            var key = $rootScope.store_id + "ItemComments";
            var cache = cacheService.get(key);
            if (pageNo || !cache) {
                $scope.pageNo = pageNo ? pageNo : "1";
                var query = {
                    content: {
                        page_no: $scope.pageNo,
                        page_size: $scope.pageSize,
                        store_id: $rootScope.store_id
                    }
                };
                cacheService.set(key, query);
            } else {
                query = clone(cache);
                $scope.queryRcache(query);
            }

            var querys = clone(query);

            dataService.commentsGet(querys).then(function(list) {
                if (list) {
                    $scope.commentslist = list.comments_list;
                    $scope.commentsTotal = list.total_count;
                }
            });
        };

        $scope.checkUpdate = function(comments_id, flag) {
            helper.myConfirm("确认操作么？", function() {
                if (flag == 1) {
                    var query = {
                        content: {
                            comments_id: comments_id,
                            check: 2
                        }
                    };
                }

                if (flag == 2) {
                    var query = {
                        content: {
                            comments_id: comments_id,
                            check: 1
                        }
                    };
                }

                dataService.commentsUpdate(query).then(function(list) {
                    if (list.Msg == "ok") {
                        helper.myAlert("success", null, null, function() {
                            $scope.getItemCommentsList($scope.pageNo);
                        });
                    } else {
                        helper.myAlert("error：" + list.Msg);
                        return false;
                    }
                });
            });
        };

        //手工增加评价
        $scope.manualcommentsAction = function() {
            $scope.manual = {};
            $scope.manual.item_id = 0;
            $scope.manual.member_id = 0;
            $scope.manual.content = "";
        };

        $scope.manualcommentsAdd = function() {
            if (!$scope.manual.item_id) {
                helper.myAlert("没有选择商品，无法评价！");
                return false;
            }
            if (!$scope.manual.member_id) {
                helper.myAlert("没有选择用户，无法评价！");
                return false;
            }
            if (!$scope.manual.content) {
                helper.myAlert("没有填写内容，无法评价！");
                return false;
            }
            var data = {
                store_id: $rootScope.store_id,
                member_id: $scope.manual.member_id,
                item_id: $scope.manual.item_id,
                content: $scope.manual.content,
                check: 2
            };
            dataService.manualcommentsAdd(data).then(function(list) {
                if (list.Msg == "ok") {
                    helper.myAlert("success", null, null, function() {
                        $state.go("item.comments");
                    });
                } else {
                    helper.myAlert("error：" + list.Msg);
                    return false;
                }
            });
        };

        $scope.itemdata2 = function(items) {
            if (items) {
                //选中商品
                $scope.checked_item = items;
                $scope.manual.item_id = items.item_id;
            }
        };

        $scope.memberdata = function(memberInfo) {
            $scope.manual.member_id = memberInfo.member_id;
        };

        $scope.importAction = function() {};

        //
        $scope.selectCatid = function(catid) {
            if (catid) {
                $scope.catid = catid;
            }
        };
        //推送到仓库
        $scope.postItemWms = function(id) {
            dataService.postItemWms(id).then(function(re) {
                // console.error("re", re);
                if (re.Msg) {
                    helper.myAlert(re.Msg);
                } else {
                    helper.myAlert("success");
                }
            });
        };

        //删除商品
        $scope.delItem = function(id) {
            helper.myConfirm("注意商品删除后无法恢复，请确认是否删除？", function() {
                var query = {
                    "item_id": id,
                    "store_id": $rootScope.store_id,
                    "partner_id": $rootScope.s_partner_id
                };
                // console.error("query", query);
                // return false;
                dataService.delItem(query).then(function(result) {
                    if (result.Msg != "ok") {
                        helper.myAlert(result.Msg);
                    } else {
                        helper.myAlert("success");
                        $scope.getItemList();
                    }
                });
            });
        };

        //批量删除商品
        $scope.delAllItem = function() {
            for (var i = 0; i < $scope.sjmodel.length; i++) {
                var query = {
                    "store_id": $rootScope.store_id,
                    "item_id": $scope.sjmodel[i].item_id,
                    "partner_id": $rootScope.s_partner_id
                };
                dataService.delItem(query).then(function(r) {

                });
            }
            helper.myAlert("success", null, 3, function() {
                $scope.getItemList($scope.pageNo);
            });
        };

        //添加数据 初始化
        $scope.addAction = function() {
            $scope.$on("event:up-tore-id", function() {
                $scope.store_id = $rootScope.store_id;
                $scope.industryCode = $rootScope.industryCode;
            });

            $scope.itemdescription = random();
            $scope.skuNewinit = [{
                pid: 0,
                name: "默认规格",
                values: [{
                        id: 0,
                        value: "默认属性",
                        mark: ""
                    },
                    {
                        id: 0,
                        value: "",
                        mark: ""
                    }
                ]
            }];

            if (!$scope.store_id) {
                return helper.myAlert("非法门店id", "#/item/list");
            }

            $scope.skuNew = [];
            $scope.parentCat = {};
            var id = $location.search().id;
            if (id) {
                $scope.GetItemOne(id);
                // console.log("商品修改 action 初始化", $scope.item);
            } else {
                $scope.item = {};
                //初始化值
                $scope.skuNew = clone($scope.skuNewinit);
                $scope.item.outer_id = "A00000" + random();
                $scope.item.title = $scope.item.outer_id + "号的商品标题";
                $scope.item.volume = 0; //体积
                $scope.item.store_id = parseInt($scope.store_id);
                $scope.item.type_id = 2;
                $scope.item.cost = 0; //成本
                $scope.item.img = "";
                // https://g-search1.alicdn.com/img/bao/uploaded/i4/imgextra/i2/188620136570582931/TB28ruZgVXXXXbuXXXXXXXXXXXX_!!12368862-0-saturn_solar.jpg_230x230.jpg
                $scope.item.maket_price = 0; //销售价
                $scope.item.prom_price = 0; //促销价
                $scope.item.note = ""; //简单备注
                $scope.item.on_shelves = 1; //是否上下
                $scope.item.is_present = 2; //是否赠品
                $scope.item.prom_flag = 2; //促销标志
                $scope.item.stock_num = 2; //库存
                $scope.item.is_present = 2; //是否赠品
                $scope.item.sale_num = 0;
                $scope.item.p_item_id = 0;
                $scope.item.weight = 0;
                $scope.item.packing_fee = 0;
                $scope.item.is_virtual = false;
                $scope.item.skus = [];
                console.error("新建：", $scope.item);
            }

            $scope.$watch(
                "skuNew",
                function(nVal, oVal) {
                    //                     console.error("nVal1111===", nVal);
                    // $scope.addNewSkuData();

                    $scope.itemSkuData = sku.skuRuCan(nVal);
                    //                     console.error("$scope.newSkus===", $scope.newSkus);

                    $scope.oldata = clone($scope.newSkus);

                    //                     console.error("$scope.oldata===", $scope.oldata);

                    if (id) {
                        $scope.newSkus = sku.addNewSkus(
                            $scope.itemSkuData,
                            $scope.item,
                            $scope.oldata
                        );
                    } else {
                        $scope.newSkus = sku.addNewSkus(
                            $scope.itemSkuData,
                            null,
                            $scope.oldata
                        );
                    }
                    _.map($scope.newSkus, function(da, ke) {
                        if (!da.sku_id) {
                            da.imgurl = $scope.item.img;
                        }
                    });
                },
                true
            );
        };

        $scope.setback = function(attch) {
            _.map($scope.newSkus, function(da) {
                if (!da.imgurl && attch) {
                    da.imgurl = attch;
                }
            })
        }
        $scope.GetItemOne = function(id) {
            dataService.itemOne(id).then(function(one) {
                if (one) {
                    if ($rootScope.is_main == 2 && (one.p_item_id != "0")) {
                        helper.message("此商品是分销商品，部分字段不支持修改！", "error");
                    }
                    $scope.Arrangement(one);
                } else {
                    helper.myAlert("没有找到该商品", null, null, function() {
                        $state.go("item.list");
                    });
                }
            });
        };

        $scope.Arrangement = function(one) {
            // console.error("one-----", one);
            var skusDateAry = [];
            _.map(one.skus, function(da, k) {
                skusDateAry.push({
                    data: da.sku_properties
                });
            });
            var fgeoneDate = [];
            var pidAry = [];
            async.mapSeries(skusDateAry, function(dss, callback) {
                    var strs = dss.data.split(";");
                    // console.error("strs==", dss.data);
                    strs = strs.filter(function(n) {
                        return n;
                    });
                    if (strs) {
                        // console.error("==========", strs);
                        async.mapSeries(strs, function(dd, callback1) {
                                var svbtrs = dd.split(":");
                                // console.error("svbtrs", svbtrs);
                                if (!pidAry[svbtrs[0]]) {
                                    dataService.itemSkuTypeGet({
                                            query: {
                                                id: svbtrs[0],
                                                name: svbtrs[2],
                                                item_id: one.item_id
                                            }
                                        })
                                        .then(function(r) {
                                            // console.error("r", r);
                                            if (r.Msg) {
                                                callback1(null, null);
                                            } else {
                                                if (r.sku_types.length > 0) {
                                                    pidAry[svbtrs[0]] = 1;
                                                    add();
                                                } else {
                                                    callback1(null, null);
                                                }
                                            }
                                        });
                                } else {
                                    add();
                                }

                                function add() {
                                    // console.error("============================");
                                    if (svbtrs[0] && svbtrs[2] && svbtrs[1] && svbtrs[3]) {
                                        fgeoneDate.push({
                                            pid: Number(svbtrs[0]),
                                            name: svbtrs[2],
                                            id: Number(svbtrs[1]),
                                            value: svbtrs[3]
                                        });
                                        callback1(null, null);
                                    }
                                }
                            },
                            function(e, r) {
                                callback(null, null);
                            }
                        );
                    } else {
                        callback(null, null);
                    }
                },
                function(e, r) {
                    $timeout(function() {
                        $scope.item = clone(one);
                        $scope.item.oldSkus = $scope.item.skus;
                        try {
                            $scope.item.description = $scope.item.description ?
                                json2html(JSON.parse($scope.item.description)) :
                                "";
                            $scope.item.vdesc = $scope.item.vdesc ?
                                json2html(JSON.parse($scope.item.vdesc)) :
                                "";
                        } catch (e) {
                            $scope.item.description = "";
                            $scope.item.vdesc = "";
                        }
                        $scope.item.delivery_addrs = $scope.item.delivery_addrs ?
                            $scope.item.delivery_addrs.split(",") :
                            null;
                        $scope.item.fgeoneDate = fgeoneDate;
                        // console.error("ddddddddddddddddddddd", $scope.item.is_virtual);
                        // $scope.item.is_virtual = $scope.item.is_virtual ? 1 : 0;
                        // console.error("ddddddddddddddddddddd", $scope.item.is_virtual);
                        $scope.updateSkuType();
                        $scope.clitem = clone($scope.item);
                        $scope.isid = one.item_id;
                    });
                }
            );

        };

        //获取增加的规格数据
        // $scope.addSku = function(sku) {
        //     if (!$scope.item.skus) {
        //         $scope.item.skus = [];
        //     }
        //     $scope.item.skus.push(skuDefault());
        // };

        //获取增加的规格数据 sku
        $scope.addNewSku = function() {
            $timeout(function() {
                $scope.skuNew = sku.addNorms($scope.skuNew);
            });
        };

        $scope.isSelected = function(value, name) {
            // console.error("value", value, name);
            if (value) {
                return true;
            } else {
                return false;
            }
        };

        //判断规格是否重复
        $scope.addNskuName = function(name, key, $event) {
            // $scope.skuNew = sku.checkNormsName($scope.skuNew, name, key);

            //原先的逻辑
            if (name) {
                _.map($scope.skuNew, function(d, k) {
                    if (d.name == name && key !== k) {
                        helper.myAlert(name + "该属性已经存在");
                        $scope.skuNew[key].name = "";
                    }
                });
            }
        };

        $scope.addNsku = function(name, val, pid, key) {
            $timeout(function() {
                var data = "1";
                _.map($scope.skuNew, function(d, k) {
                    if (val) {
                        if (d.name == name) {
                            _.map(d.values, function(isvd, kk) {
                                if (isvd.value == val && key !== kk) {
                                    helper.myAlert(name + "[" + val + "]" + "该类型已经存在");
                                    d.values[key].value = "";
                                    data = "2";
                                }
                            });
                        }
                    }
                });
                return data;
            }).then(function(data) {
                if (data == "1" && val) {
                    $scope.addValues(name, pid, key);
                }
            });
        };

        //增加 values 数据
        $scope.addValues = function(name, pid, key) {
            $scope.skuNew = sku.addAttribute($scope.skuNew, name, pid, key);
            //             console.error($scope.skuNew);
        };

        //增加属性
        $scope.addNewSkuVaue = function(name, va, $event, key, pid) {
            var checkbox = $event.target;
            if (checkbox.checked) {
                // 选中时 增加新的 数据
                if (name && va) {
                    $scope.addValues(name, pid);
                }
            } else {
                //取消选中 删除 取消的值
                if (name && va) {
                    _.map($scope.skuNew, function(d, k) {
                        if (d.name == name) {
                            if (d.values.length == 1) {
                                d.values[0].value = "";
                            } else {
                                _.map(d.values, function(isvd, kk) {
                                    if (key == kk) {
                                        d.values.splice(kk, 1);
                                    }
                                });
                            }
                        }
                    });
                }
            }
        };

        //添加api 值
        $scope.addNewSkuData = function() {
            // console.log("$scope.skuNew", $scope.skuNew);
            if (!$scope.item.item_id) {
                $scope.item.skus = [];
            }
        };

        $scope.skuPropertiesData = {};

        //分解sku 组装淘宝格式 显示
        $scope.updateSkuType = function() {
            // console.error("updateSkuType", $scope.item);
            // console.error("updateSkuType", $scope.item.fgeoneDate);
            if ($scope.item) {
                if ($scope.item.fgeoneDate) {
                    var arr = oneConTwo($scope.item.fgeoneDate); //将一维数组 转换有父子关系的二维数组
                    var aryData = unique5(arr); //去除重复值；
                    if (aryData) {
                        var newata = [];
                        _.map(aryData, function(dd, kk) {
                            newata.push({
                                pid: dd.pid,
                                name: dd.name,
                                values: []
                            });
                            var len = dd.values;
                            for (var j = 0; j < len.length; j++) {
                                if (len[j]) {
                                    len[j].type = len[j].id;
                                    newata[kk].values.push(len[j]);
                                }
                                if (len.length == j + 1) {
                                    newata[kk].values.push({
                                        id: 0,
                                        value: "",
                                        mark: ""
                                    });
                                }
                            }
                        });
                        $scope.skuNew = newata;
                        // console.error("skuNew---->", $scope.skuNew);
                    }
                }
                // console.error("skuNew---->", $scope.skuNew.length);
                if ($scope.skuNew.length == 0) {
                    $scope.skuNew = clone($scope.skuNewinit);
                    $scope.uptype = 1;
                }
            }
        };

        //将多个带有父子关系的一维数组，转换为二维数组
        function oneConTwo(fgeoneDate) {
            var map = {};
            var arr = [];
            //             console.error("fgeoneDate=", fgeoneDate);
            for (var i = 0; i < fgeoneDate.length; i++) {
                var di = fgeoneDate[i];
                var n = di.pid;
                //console.error("map[n]=", n);

                if (!map[n]) {
                    //先判断 pid是否有只 有值 先给父级赋值

                    map[n] = di.name;
                    arr.push({
                        pid: n,
                        name: di.name,
                        values: [{
                            id: di.id,
                            value: di.value
                        }]
                    });
                } else {
                    for (var j = 0; j < arr.length; j++) {
                        var aj = arr[j];
                        if (aj.pid == n) {
                            //pid相等的时候，在给子类赋值
                            arr[j].values.push({
                                id: di.id,
                                value: di.value
                            });
                            break;
                        }
                    }
                }
            }
            //             console.error("arrarrarrarrarrarrarrarr=", arr);
            return arr;
        }

        //去除二维数组中 重复 的一维数组
        function unique5(arrays) {
            _.map(arrays, function(arra, k) {
                var array = arra.values;
                for (var i = 0, l = array.length; i < l; i++) {
                    for (var j = i + 1; j < l; j++) {
                        //判断 第一个和第二个数组 内容是否相同 ，id相同 就代表数据相同
                        if (array[i].id === array[j].id) {
                            delete arra.values[i];
                            j = ++i;
                        }
                    }
                }
            });
            // console.log("arraysarraysarraysarrays=", arrays);
            return arrays;
        }

        function skuDefault() {
            var sku_outer_id = "S00" + random(11111, 99999);
            return {
                sku_outer_id: sku_outer_id,
                sku_properties: sku_outer_id + "的名字",
                sku_price: 100,
                sku_stocks: 1 //条码
            };
        }

        $scope.infoAction = function() {
            var id = $location.search().id;
            if (id) {
                dataService.itemOne(id).then(function(one) {
                    if (one) {
                        $scope.item = one;
                        $scope.isinfo = "1";
                    } else {
                        helper.myAlert("No data found", null, null, function() {
                            $state.go("item.list");
                        });
                    }
                });
            } else {
                helper.myAlert("No data found", null, null, function() {
                    $state.go("item.list");
                });
            }
        };

        //增加规格
        $scope.itemSkuAdd = function(item_id, sku, $event) {
            var data = clone(sku);
            data.item_id = item_id;
            // console.log("data", data);
            zuzhuangItem(data, 1, $event, sku);
        };

        $scope.itemSkuUpdate = function(item_id, sku_id, sku, $event) {
            sku.item_id = item_id;

            dataService.itemSkuUpdate(sku).then(function(r) {
                if (r.Msg) {
                    helper.myTip("error:" + r.Msg, $event.currentTarget);
                } else {
                    helper.myTip("success", $event.currentTarget);
                    return;
                }
            });
        };

        //status=1正常，2冻结
        $scope.itemSkuStatusUpdate = function(data, status, type) {
            helper.myConfirm("confirm operation", function() {
                var sku_id = data.sku_id ? data.sku_id : "";
                dataService.itemStatusUpdate($scope.item.item_id, status, sku_id).then(
                    function(r) {
                        data.status_id = status;
                    },
                    function(error) {
                        helper.myAlert("api error:" + error);
                    }
                );
            });
        };

        $scope.skuDelete = function(sku_id, index) {
            if (sku_id) {
                dataService.itemskuDelete(sku_id).then(function(r) {
                    if (r.Msg) {
                        helper.myAlert(" api error:" + r.Msg);
                    } else {
                        $scope.item.skus.splice(index, 1);
                        helper.myAlert("success");
                    }
                });
            }
        };

        //测试商品directives
        $scope.checkItem = function(items) {
            $scope.items = items;
        };

        //创建 商品
        $scope.itemAdd = function($event) {
            var i = 0;
            _.map($scope.itemSkuData, function(dd, kk) {
                if (dd) {
                    i = i + 1;
                }
            });
            if (!i) {
                helper.myAlert("规格不能为空");
                return;
            }

            //检测价格
            console.error("$scope.item", $scope.item);
            // return false;
            helper.myTip("保存中,请勿操作!", $event.currentTarget, null, 5);
            // return false;
            sku.finishSkuData(
                $scope.itemSkuData,
                $scope.newSkus,
                $scope.item.item_id,
                function(skusData) {
                    $scope.item.tag_ids = "";
                    _.map($scope.item.label, function(da, ke) {
                        if ($scope.item.tag_ids) {
                            $scope.item.tag_ids = $scope.item.tag_ids + "," + da.label_id;
                        } else {
                            $scope.item.tag_ids = da.label_id;
                        }
                    });
                    console.error("$scope.industryCode", $scope.industryCode);
                    if ($scope.item.xtype == 1 && ($scope.industryCode == 27 || $scope.industryCode == 28)) {
                        //只有是跨境商品进行检测是否关联备案商品
                        $scope.getHgSku(skusData);
                    } else {
                        $scope.saveItem(skusData);
                    }
                }
            );
        };
        $scope.saveItem = function(skusData) {
            console.error("skusData", skusData);
            // return false;
            if ($scope.item.p_item_id && $scope.item.p_item_id !== "0") {
                $scope.TestingPrice(skusData);
            } else {
                $scope.saveItemData(skusData);
            }
        }
        $scope.TestingPrice = function(skusData) {
            dataService.itemOne($scope.item.p_item_id).then(function(one) {
                if (one) {
                    var price = 0;
                    _.map(skusData, function(sku, ke) {
                        if (sku.status_id == 1) {
                            if (!price) {
                                price = sku.sku_price;
                            }
                            if (sku.sku_price < price) {
                                price = sku.sku_price;
                            }
                        }
                    });
                    console.error("子店数据", price, skusData);
                    console.error("主店数据", one.price);
                    //主店商品单价小于分店商品的价格的时候需要提升下
                    if (price < one.price) {
                        helper.myAlert("此商品是子店商品，商品价格(" + price + ")不能小于主店的商品价格(" + one.price + ")");
                        return;
                    } else {
                        $scope.saveItemData(skusData);
                    }
                } else {
                    $scope.saveItemData(skusData);
                }
            });
        }

        $scope.saveItemData = function(skusData) {
            console.error("skusData", skusData);
            // return false;
            if ($scope.item.item_id) {
                var dte = [];
                _.map(skusData, function(da, k) {
                    if (da.sku_id) {
                        if (da.tax_rate) {
                            da.tax_rate = parseFloat(da.tax_rate);
                        }
                        dte[da.sku_id] = da;
                    }
                });
                async.mapSeries(
                    $scope.item.oldSkus,
                    function(data, cb) {
                        if (!dte[data.sku_id] && data.sku_id) {
                            var query = {
                                item_id: $scope.item.item_id,
                                sku_id: data.sku_id
                            };
                            dataService.itemDelete(query).then(function(r) {
                                cb(null);
                            });
                        } else {
                            cb(null);
                        }
                    },
                    function(e, d) {
                        delete $scope.item.oldSkus;
                        delete $scope.item.fgeoneDate;
                        $scope.item.skus = skusData;
                        //执行添加sku
                        $scope.itemUpdateFront($scope.item);
                    }
                );
            } else {
                $scope.item.skus = skusData;
                $scope.derItemAdd($scope.item);
            }
        };

        $scope.getHgSku = function(skusData) {
            var type = false;
            async.mapSeries(
                skusData,
                function(data, cb) {
                    if (data.sku_outer_id) {
                        var query = {
                            SKU: data.sku_outer_id
                        };
                        dataService.customsItemsGet(query).then(function(r) {
                            if (r.list.length == 0) {
                                type = data.sku_outer_id;
                                helper.message("商品外部编码" + type + "填写不正确！请确保该编码有对应的海关商品！");
                            }
                            cb(null);
                        });
                    } else {
                        cb(null);
                    }
                },
                function(e, d) {
                    $scope.saveItem(skusData);
                }
            );
        };

        //修改的时候添加 sku 数据
        $scope.itemUpdateFront = function(itemsData) {
            //console.error("====================================");
            async.mapSeries(
                itemsData.skus,
                function(data, cb) {
                    if (!data.sku_id) {
                        data.tax_rate = parseFloat(data.tax_rate);
                        var query = {
                            item_id: itemsData.item_id,
                            skus: [data],
                            store_id: $rootScope.store_id
                        };
                        dataService.itemAdd(query).then(function(r) {
                            cb(null);
                        });
                    } else {
                        cb(null);
                    }
                },
                function(e, d) {
                    console.error("itemsData", itemsData);
                    $scope.itemUpdate($scope.item);
                }
            );
        };

        $scope.derSkusAdd = function(data, $event, sku) {
            dataService.itemSkuAdd(data).then(function(r) {
                if (r.Msg) {
                    helper.myTip("error:" + r.Msg, $event.currentTarget);
                } else {
                    sku.status_id = 1;
                    sku.sku_id = r.sku_id;
                    // $scope.GetItemOne(data.item_id);
                }
            });
        };

        $scope.derItemAdd = function(itemsData) {
            console.log("请求商品添加api的数据", itemsData);
            // return false;
            var itemcloneData = $scope.HandleImage(itemsData);
            // console.error("itemcloneData===================", itemcloneData);

            //邮费模板判断 is_incl_postage == 2 设置了模板
            if (itemcloneData.is_incl_postage == 2) {
                $scope.getFareOne(itemcloneData.fare_id).then(function(valuation_model) {
                    if (valuation_model == 2) {
                        //重量计费模板
                        if (itemcloneData.weight == 0) {
                            helper.message("设置了重量计费模板，请设置商品重量，否则无法保存！", "error");
                            return false;
                        } else {
                            $scope.item_add(itemcloneData, itemsData);
                        }
                    } else {
                        $scope.item_add(itemcloneData, itemsData);
                    }
                });
            } else {
                //包邮模板直接更新
                //包邮模板的话，需要fare_id设置成0，否则会导致邮费模板无法删除
                itemcloneData.fare_id = 0;
                $scope.item_add(itemcloneData, itemsData);
            }
        };

        $scope.item_add = function(itemcloneData, itemsData) {
            dataService.itemAdd(itemcloneData).then(function(r) {
                if (r.Msg) {
                    helper.myAlert("api error:" + r.Msg);
                } else {
                    $scope.addRelation(itemsData.label, r.item_id);
                    sku.updateSkuTypeItemid(itemsData.skus, r.item_id, function() {
                        helper.myAlert("success", null, null, function() {
                            $state.go("item.list");
                        });
                    });
                }
            });
        }

        //
        $scope.addRelation = function(label, item_id) {
            _.map(label, function(da) {
                var data = {
                    label_id: da.label_id,
                    item_id: item_id,
                    store_id: $rootScope.store_id
                };
                dataService.itemLabelRelationAdd(data).then(function(r) {
                    if (r.Msg) {
                        helper.myAlert("api error:" + r.Msg);
                    }
                });
            });
        };
        $scope.itemUpdate = function(itemsData) {
            var itemcloneData = $scope.HandleImage(itemsData);

            //邮费模板判断 is_incl_postage == 2 设置了模板
            if (itemcloneData.is_incl_postage == 2) {
                $scope.getFareOne(itemcloneData.fare_id).then(function(valuation_model) {
                    if (valuation_model == 2) {
                        //重量计费模板
                        if (itemcloneData.weight == 0) {
                            helper.message("设置了重量计费模板，请设置商品重量，否则无法保存！", "error");
                            return false;
                        } else {
                            $scope.item_update(itemcloneData, itemsData);
                        }
                    } else {
                        $scope.item_update(itemcloneData, itemsData);
                    }
                });
            } else {
                //包邮模板直接更新
                itemcloneData.fare_id = 0;
                $scope.item_update(itemcloneData, itemsData);
            }
        };

        $scope.item_update = function(itemcloneData, itemsData) {
            // p_item_id有值的话，把p_item_id过滤掉
            if (itemcloneData.p_item_id) {
                delete itemcloneData.p_item_id;
            }
            dataService.itemUpdate(itemcloneData).then(function(r) {
                if (r.Msg) {
                    helper.myAlert(" api error:" + r.Msg);
                } else {
                    $scope.addRelation(itemsData.label, r.item_id);
                    sku.updateSkuTypeItemid(itemsData.skus, r.item_id, function() {
                        helper.myAlert("success", null, null, function() {
                            $state.go("item.list");
                        });
                    });
                }
            });
        }

        //获取邮费模板
        $scope.getFareOne = function(fare_id) {
            var query = {
                "query": {
                    "fare_id": fare_id
                }
            };
            return dataService.postfeeGet(query).then(function(result) {
                if (result) {
                    return result.fare_temp[0].valuation_model;
                }
            });
        }

        $scope.batchSaveItem = function() {
            // console.error("sjmodel", $scope.sjmodel);

            if ($scope.sjmodel) {
                async.mapSeries($scope.sjmodel,
                    function(one, callback) {
                        dataService.itemUpdate(one).then(function(r) {
                            if (r.Msg) {
                                callback(null, null);
                            } else {
                                callback(null, null);
                            }
                        });
                    },
                    function(e, r) {
                        helper.myAlert("success", null, null, function() {
                            $scope.getItemList($scope.pageNo);
                        });
                    }
                );
            }
        }

        //处理上传图片
        $scope.HandleImage = function(itemsData) {
            var isitemsData = clone(itemsData);
            try {
                isitemsData.description = JSON.stringify(
                    html2json(isitemsData.description)
                );
                if (isitemsData.vdesc) {
                    isitemsData.vdesc = JSON.stringify(
                        html2json(isitemsData.vdesc)
                    );
                }
            } catch (e) {
                isitemsData.description = "";
                isitemsData.vdesc = "";
            }
            try {
                isitemsData.delivery_addrs = isitemsData.delivery_addrs.toString();
            } catch (e) {
                isitemsData.delivery_addrs = isitemsData.delivery_addrs ?
                    isitemsData.delivery_addrs[0] :
                    "";
            }
            // console.error("itemsData", isitemsData);
            isitemsData = $scope.ItemPrice(isitemsData);
            return isitemsData;
        };
        //商品价格
        $scope.ItemPrice = function(isitemsData) {
            var pic = 0;
            _.map(isitemsData.skus, function(sku, ke) {
                if (sku.status_id == 1) {
                    if (!pic) {
                        pic = sku.sku_price;
                    }
                    if (sku.sku_price < pic) {
                        pic = sku.sku_price;
                    }
                }
                if (!sku.imgurl) {
                    sku.imgurl = isitemsData.img;
                }
                sku.tax_rate = parseFloat(sku.tax_rate);
            });
            isitemsData.price = pic;
            return isitemsData;
        }
        $scope.batchItemShelvesUpdate = function(type) {
            if ($scope.sjmodel) {
                async.mapSeries($scope.sjmodel,
                    function(one, callback) {
                        if (one.on_shelves !== type) {
                            dataService.itemUpdate({
                                    on_shelves: type,
                                    item_id: one.item_id
                                })
                                .then(function(r) {
                                    if (r.Msg) {
                                        callback(null, null);
                                    } else {
                                        callback(null, null);
                                    }
                                });
                        } else {
                            callback(null, null);
                        }
                    },
                    function(e, r) {
                        helper.myAlert("success", null, null, function() {
                            $scope.getItemList($scope.pageNo);
                        });
                    }
                );
            }
        };

        $scope.batchSavefreight = function(data) {
            if (data) {
                // console.error("data", data, $scope.sjmodel);
                async.mapSeries($scope.sjmodel, function(item, callback) {
                        var itemdata = {
                            item_id: item.item_id,
                            is_incl_postage: 2,
                            fare_id: data,
                        };
                        dataService.itemUpdate(itemdata).then(function(list) {
                            if (list.Msg) {
                                //有值
                                callback(null, null);
                            } else {
                                callback(null, null);
                            }
                        });
                    },
                    function(e, r) {
                        helper.myAlert("success");
                    });

            }
        };

        $scope.itemShelvesUpdate = function(item, type) {
            if (item) {
                var itemdata = {
                    item_id: item.item_id,
                    on_shelves: type,
                    store_id: item.store_id
                };
                // item.on_shelves = type;
                dataService.itemUpdate(itemdata).then(function(r) {
                    if (r.Msg) {
                        helper.myAlert("api error:" + r.Msg);
                    } else {
                        helper.myAlert("success", null, null, function() {
                            $scope.getItemList($scope.pageNo);
                        });
                    }
                });
            }
        };

        //虚拟商品列表
        $scope.virtualAction = function() {
            $scope.skuTotal = 0;
            $scope.pageSize = 10;
            $scope.getVirtualist();
            $scope.is_main = $rootScope.is_main;

            $scope.$on("event:up-store-id", function() {
                $scope.store_id = $rootScope.store_id;
                $scope.is_main = $rootScope.is_main;

                $scope.getVirtualist();
            });
        }

        $scope.getVirtualist = function(pageNo) {
            var query = {};
            $scope.pageNo = pageNo ? pageNo : 1;
            query = {
                page_no: $scope.pageNo,
                page_size: $scope.pageSize,
                store_id: $scope.store_id
            };
            if ($scope.sku_id) {
                query.sku_id = $scope.sku_id;
            }

            dataService.virtualSkuGet(query).then(function(list) {
                if (list) {
                    if ($scope.sku_id) {
                        $scope.sku2skus = list.virtual_list[0];
                        $scope.checked_item = $scope.sku2skus.sku_data;
                        $scope.checked_item1 = $scope.sku2skus.s_sku;
                    } else {
                        $scope.virtual_list = list.virtual_list;
                    }
                    $scope.total_count = list.total_count;
                }
            });
        }

        //sku2skus 虚拟商品组合
        $scope.sku2skusAction = function() {
            var sku_id = $location.search().sku_id;
            if (sku_id) {
                $scope.sku_id = sku_id;
                $scope.getVirtualist();
            } else {
                $scope.sku2skus = {
                    "sku_id": "",
                    "sku_outer_id": ""
                };
            }
        }

        //选择主sku回调
        $scope.itemdata = function(items) {
            //商品信息是多维数组时
            if (items && items.sku_data) {
                //选中商品的 sku_id
                $scope.sku2skus.sku_id = items.sku_data.sku_id;
                $scope.sku2skus.sku_outer_id = items.sku_data.sku_outer_id;
                //选中商品
                $scope.checked_item = items.sku_data;
            }
        }

        //选择子sku回调
        $scope.itemdata1 = function(items) {
            //商品信息是多维数组时
            if (items) {
                //选中商品
                $scope.checked_item1 = items;
            }
        }

        //sku2skus add
        $scope.sku2skusAdd = function() {
            //主sku_id是否存在
            if (!$scope.sku2skus.sku_id) {
                helper.myAlert("没有选择主sku，不能保存！");
                return false;
            }

            //子sku
            if ($scope.checked_item1.length == 0) {
                helper.myAlert("没有选择子sku，不能保存！");
                return false;
            }

            //旧数据增加sku_outer_id
            if (!$scope.sku2skus.sku_outer_id) {
                $scope.sku2skus.sku_outer_id = $scope.checked_item.sku_outer_id
            }

            //子sku数量是否设置
            var a = [];
            for (var i in $scope.checked_item1) {
                // console.error("son", $scope.checked_item1[i]);
                var son = $scope.checked_item1[i];
                if (!son.num || son.num == 0) {
                    helper.myAlert("数量没有设置或者设置为0，不能保存");
                    break;
                } else {
                    // 选中的子sku sku_id不能和父sku_id相等
                    if ($scope.sku2skus.sku_id == son.sku_id) {
                        helper.myAlert("子sku_id不能和上一级选中的sku_id相同！");
                        break;
                    }

                    a.push({
                        "s_sku_id": son.sku_id,
                        "s_sku_outer_id": son.sku_outer_id,
                        "num": son.num
                    });
                }
            }

            $scope.sku2skus.s_sku = a;
            $scope.sku2skus.store_id = $rootScope.store_id;

            //edit true
            if ($scope.sku_id) {
                $scope.sku2skus.edit = true;
            }

            // console.error("sku2skus", $scope.sku2skus);
            // return false;
            dataService.sku2skusAdd($scope.sku2skus).then(function(r) {
                // console.error("r", r);
                if (r.Msg == "ok") {
                    helper.myAlert("success", "#/item/virtual");
                } else {
                    helper.myAlert("error:" + r.Msg);
                    return false;
                }
            });
        }

        $scope.deleteSkuItem = function(index) {
            // console.error("index", index);
            $scope.checked_item1.splice(index, 1);
        }

        //删除商品
        $scope.deleteVirtualItem = function(sku_id, s_sku_id) {
            if (!sku_id || !s_sku_id) {
                helper.myAlert("sku为空，不能删除！");
                return false;
            }
            var data = {
                "sku_id": sku_id,
                "s_sku_id": s_sku_id,
                "store_id": $rootScope.store_id
            };

            dataService.sku2skusDelete(data).then(function(r) {
                if (r.Msg == "ok") {
                    helper.myAlert("success");
                    $scope.getVirtualist();
                } else {
                    helper.myAlert("error:" + r.Msg);
                    return false;
                }
            });
        }

        //删除整条组合商品
        $scope.delVirtual = function(sku_id) {
            helper.myConfirm('确定删除组合商品么？', function() {
                dataService.delVirtual({
                    'sku_id': sku_id,
                    'store_id': $rootScope.store_id
                }).then(function(result) {
                    if (result.Msg == "ok") {
                        helper.myAlert("success");
                        $scope.getVirtualist();
                    } else {
                        helper.myAlert("error：" + result.Msg);
                        return false;
                    }
                });
            });
        }
    }
})();